package servlet;

import model.Page;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/user_list")
public class AdminUserListServlet extends HttpServlet {
    private UserService uService = new UserService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo = 1; // 默认页码为 1
        if (request.getParameter("pageNo") != null) {
            try {
                pageNo = Integer.parseInt(request.getParameter("pageNo")); // 获取请求中的页码
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (pageNo <= 0) {
            pageNo = 1; // 如果页码小于等于 0，设置为 1
        }
        Page p = uService.getUserPage(pageNo); // 获取分页数据
        if (p.getTotalPage() == 0) {
            p.setTotalPage(1); // 如果总页数为 0，设置为 1
            p.setPageNo(1);
        } else {
            if (pageNo >= p.getTotalPage() + 1) {
                p = uService.getUserPage(pageNo); // 如果页码超出范围，重新获取数据
            }
        }
        request.setAttribute("p", p); // 将分页数据传递给 JSP
        request.getRequestDispatcher("/admin/user_list.jsp").forward(request, response); // 转发到 JSP 页面
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
